import React, { Component } from 'react'
import {NavBar,InputItem,Button,Toast} from 'antd-mobile'
import {codeReg,phoneReg} from '../../utils/reg'
import {COUNTDOWN} from '../../constant'
import axios from '../../ajax/axios'
import './Login.less'

export default class Login extends Component {
	state = {
		phone:'',
		code:'',
		countdown:COUNTDOWN,
		canClick:true
	}
	render() {
		const {canClick,countdown} = this.state
		return (
			<div>
				{/* 顶部导航区域 */}
				<NavBar
					mode="light" //导航栏颜色
					// icon={<Icon type="left" />} //导航栏左侧区域
					// onLeftClick={() => console.log('onLeftClick')} //左侧区域点击回调
					// rightContent={[
					// 	<Icon key="0" type="search" />,
					// 	<Icon key="1" type="ellipsis" />,
					// ]}
				>验证码登录</NavBar>
				<div className="content">
					<InputItem clear onChange={this.saveFromData('phone')} placeholder="输入手机号"/>
					<div className="code-group">
						<InputItem clear onChange={this.saveFromData('code')} placeholder="输入验证码"/>
						<button 
							className={canClick ? 'code-btn' : 'code-btn disable'} 
							onTouchStart={this.getCode}
						>获取验证码{canClick ? '' : `(${countdown})`}</button>
					</div>
					<Button type="primary" onTouchStart={this.login}>登录</Button>
				</div>
			</div>
		)
	}

	componentWillUnmount(){
		clearInterval(this.tid)
	}

	//保存表单数据到state
	saveFromData = (type)=>{
		return (value)=>{
			if(type==='phone' && !phoneReg.test(value)) value=''
			else if(type==='code' && !codeReg.test(value)) value=''
			this.setState({[type]:value})
		}
	}

	//获取验证码的逻辑
	getCode = ()=>{
		//从状态中获取手机号、按钮是否可以点击
		const {phone,canClick} = this.state
		//如果按钮不可点击，终止逻辑
		if(!canClick) return
		//如果手机号不合法，提示并终止逻辑
		if(!phone) return Toast.fail('手机号不合法')
		//发送请求前，让按钮不可点击
		this.setState({canClick:false})
		//开启定时器更新时间
		this.tid = setInterval(()=>{
			//获取当前的倒计时
			let {countdown} = this.state
			countdown--
			if(countdown <=0 ){
				clearInterval(this.tid)
				return this.setState({countdown:COUNTDOWN,canClick:true})
			}
			this.setState({countdown})
		},1000)

		console.log('发送请求获取验证码')
	}

	login = async()=>{
		const {phone,code} = this.state
		let errorArr = []
		if(!phone) errorArr.push('手机号')
		if(!code) errorArr.push('验证码')
		if(errorArr.length) return Toast.fail(errorArr.join('、')+'不合法')
		const result = await axios.get('/persons')
		//亲手判断业务逻辑是否成功
		if(result.status===1) {
			console.log(result)
			this.props.history.replace('/center')
		}
		else Toast.fail(result.msg)
		
	}
}
